package Server;



import java.io.BufferedReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Stack;


public class ServerThread extends Thread{

	//Initialize the variables
	protected DatagramSocket dsSocket;
	DatagramPacket dpRecievePacket;
	protected BufferedReader brIn = null;
	protected boolean bLoop = true;
	static final int iPort_Number = 5678;
	public static Stack<String> stServer = new Stack<String>();
     
     public void run() {
    	 try {
			dsSocket = new DatagramSocket(iPort_Number);
		} catch (SocketException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
         while (bLoop) {
             try {
                 byte[] bRecievePacket = new byte[1024];
                 
                 // receive request
                  dpRecievePacket = new DatagramPacket(bRecievePacket, bRecievePacket.length);
                  System.out.println("hi");

                
                 dsSocket.receive(dpRecievePacket);
                 
                 System.out.println(dpRecievePacket);
                
                 String sClientRequest = new String(dpRecievePacket.getData());
                 System.out.println(sClientRequest);
                 fnController(sClientRequest);
                 
             } catch (IOException e) {
                 e.printStackTrace();
 	  bLoop = false;
             }
         }
         dsSocket.close();
     }

     public void fnController (String sClientReq) throws IOException{
    	 System.out.println("hi2");
    	 int iPosition = sClientReq.indexOf("^");
    	 if (sClientReq.charAt(iPosition - 1) == '1') {
     			stServer.push(sClientReq.substring(iPosition + 4,
 				sClientReq.length()));
     			System.out.println(stServer);
     			
 		} else if (sClientReq.charAt(iPosition - 1) == '2') {
 			if (!stServer.empty()) {
 				fnResponseClient(stServer.pop().toString());
 			}
 		} else if (sClientReq.charAt(iPosition - 1) == '3') {
 			
 			fnResponseClient(stServer.toString());
 		} else 
 			try {
 				System.out.println("Socket Server closed");
 				dsSocket.close();
 			} catch (Exception e) {
 				System.out.println(e);
 			}
 		
    	 
    	 
     }
     
     public void fnResponseClient(String sResponse) throws IOException{
    	 byte[] bSend = new byte[1024];
 		InetAddress IPAddress = dpRecievePacket.getAddress();
 		int port = dpRecievePacket.getPort();
 		bSend = sResponse.getBytes();
 		DatagramPacket dpSendReply = new DatagramPacket(bSend,
 				bSend.length, IPAddress, port);
 		dsSocket.send(dpSendReply);
     }
}
